Introduction
It’s time to go back to basic arithmetic for a while, because while basic math works more or less how you’d think, there are some important things you have to remember when doing math in your programs.
Integers
Integer math is pretty much exactly the same as what you’re familiar with. Adding two integers adds them, subtracting two integers subtracts them, and multiplying two integers multiplies them. To add two values, put a plus sign between them, to subtract two values put a dash between them, and to multiply two values put an asterisk between them. You can chain as many operations together as you want. However, do remember that your math operation will not do anything itself—you must assign the result to another variable.
addResult = valueOne + 15; multiply = x * y * z; result = 5 - numSets + 23;
Integer Division
This is where programming math starts to vary a bit from the way you’ve learned it in your math classes. You’ll remember that integers cannot store any fractional values, so what happens if you divide two integers that don’t divide evenly? Well, the short answer is the fractional part is chopped off, or truncated. If you think of the answer you should get, you’ll just get the part before the decimal point. To be clear, this doesn’t round your value—it just truncates it. This doesn’t only apply to division with integers—this will happen any time you try to assign a non-integer value to an integer. Examples:
result = 10 / 7;
This will make result hold the value 1, since 10 divided by 7 is about 1.43.
divResult = 34 / 50;
This will make divResult hold the value 0, since 34 / 50 is 0.68.
int value = -1.5;
This will make value hold the value -1, since it cannot hold the .5 part.
Floating Point
Here’s a quick foray back into the realm of normal: floating point math works exactly as you’d expect it. However, know that the larger value a floating point variable holds, the less precise the value is. This is because the value is stored in scientific notation—the larger the exponent, the less room there is for the precise value.
Modulo
There is another basic mathematical operation that you may not have used before—the modulo. The modulo operation can only be used between two integers, giving you the remainder of dividing the left value into the right one. It is used in the same way as the other basic operators, except you use the symbol ‘%’.
modResult = 12 % 13;
This evaluates to 12, as it is the remainder from dividing 13 into 12.
anotherMod = 15 % 5;
This evaluates to zero, as five divides cleanly into 15.
finalMod = 7 % 3;
This evaluates to one, as it is the remainder from dividing 3 into 7.
Order of Operations
The order of operations in C++ (more commonly referred to as operator precedence) is mostly the same as it is in formal math, with a few exceptions. Additionally, just as in formal math, you can force anything to become top priority by wrapping it in parenthesis. If you’re not sure if a statement will evaluate the way you want it to, don't be afraid to make liberal use of parenthesis. For a more detailed listing, look here.
Order | Rule |
1 | Parenthesized operations, using all of these rules. |
2 | Multiplication, division, and modulo from left to right. |
3 | Addition and subtraction from left to right. |
4 | The assignment operator. |
Combining Math and Assignment
There will often be times when you want to do something to a variable itself, and not assign the new value to a different variable. With the previous information, you could write statements such as...
var = var + 5;
...but there is a much easier and quicker way to do this. This is with combined math and assignment operators. These include ‘+=’, ‘-=’, ‘/=’, ‘*=’, and ‘%=’. These new operators are simply contractions of longer statements.
var += 5 /*is equivalent to writing*/ var = var + 5 result *= value + 1 /*is equivalent to writing*/ result = result * (value + 1)
And so on. Finally, there is an even quicker way to add or subtract one from a variable: the increment and decrement operators. These are ‘++’ and ‘--‘ respectively.
value++ /*is equivalent to writing*/ value += 1 /*which is also equivalent to writing*/ value = value + 1 var-- /*is equivalent to writing*/ var -= 1 /*which is also equivalent to writing*/ var = var - 1
Character Math
There is one more short topic that you might not expect. Remember that characters are technically a form of integer? Well, you can use characters with all of these mathematical operators. While you don’t need to know the number that corresponds to each character, you should know that the alphabet is a range of 26 consecutive integers. This means that if you were to increment the character ‘b’, you would get the character ‘c’. The same rule holds true for capital letters as well, but there isn’t a super simple relationship between the lowercase and capital letters. However, as an example of character math, you can transform a lowercased letter to a capital letter with the following statement...
capital = lowercase – ‘a’ + ‘A’;
By subtracting ‘a’ from the variable "lowercase", you get the offset from ‘a’, meaning if the lowercase letter was a ‘c’, you would get two, because it is two letters away from ‘a’. Then, the offset is added to ‘A’, producing the same letter as before, but as a capital. For example, if the offset was two, you would go two letters over from ‘A’, and get ‘C’.
cmath
Finally, you may have noticed that I haven’t mentioned anything about ways to do other operations like take a number to a power, or take the sine of a number, or round a number, etc. That’s because these functions aren’t actually part of the C++ language. However, that doesn’t mean you have to program them yourself. There is a library (just like "iostream") called "cmath" that includes many general math functions. Here’s a list of some of the most useful...
Function | Use |
cos() | cosine |
sin() | sine |
tan() | tangent |
acos() | inverse cosine |
asin() | inverse sine |
acos() | inverse cosine |
atan() | inverse tangent |
exp() | exponential |
log() | natural logarithm |
log10() | logarithm base 10 |
pow() | number to a power |
sqrt() | square root |
ceil() | round up |
floor() | round down |
round() | round |
abs() | absolute value |